//
//  HTOauthViewController.swift
//
//https://api.weibo.com/oauth2/authorize?client_id=2663991700&redirect_uri=http://www.baidu.com/
//https://api.weibo.com/oauth2/authorize?client_id=2331150087&redirect_uri=http://www.baidu.com/
//App Key:2663991700
//http://www.baidu.com/
//  Created by whtapple on 3/24/16.
//
//

import UIKit
import  SVProgressHUD
///获得授权控制器
class HTOauthViewController: UIViewController {
    ///在加载 View时，将self.view换成 webView
    override func loadView() {
        //加载 view
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //得到 URL
        let urlString = "https://api.weibo.com/oauth2/authorize"
        let fullstring = "\(urlString)?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: fullstring)
        //创建请求
        let request = NSURLRequest(URL: url!)
        //加载请求
        webView.loadRequest(request)
        //弹出正在加载提示
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.None)
        //创建 navigationbar的两个按钮
        setUpNavigationItem()
    }
    //关闭
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //创建按钮的方法
    func setUpNavigationItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style:UIBarButtonItemStyle.Plain, target: self, action: "autofill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style:UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    }
    //填充回调
    @objc private func autofill(){
        let jsCode = "document.getElementById('userId').value='13650718762';document.getElementById('passwd').value='201314'"
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    //取消回调
    func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: -懒加载webView
    private lazy var webView: UIWebView = UIWebView()
}
//MARK: -扩展HTOauthViewController 实现 UIWebViewDelegate
extension HTOauthViewController: UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
//        print("\(NSHomeDirectory())")
    }
    //    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    //        let urlstring = request.URL!.absoluteString
    //        print("\(urlstring)")
    //        if(!urlstring.hasPrefix(redirect_uri)){
    //            return true
    //        }else{
    //            let query = request.URL?.query
    //            let codestring = "code="
    //            if query!.hasPrefix(codestring) {
    //                let nsquery = query! as NSString
    //                let code = nsquery.substringFromIndex(codestring.characters.count)
    //                print("\(code)")
    //            }
    //            return true
    //        }
    //    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlstring = request.URL!.absoluteString
        //        print("\(NSHomeDirectory())")
        //        print("\(urlstring)")
        //不是授权回调地址不管他
        if(!urlstring.hasPrefix(redirect_uri)){
            return true
        }else{
            //是授权回调地址，拦截
            let query = request.URL?.query
            //说明点击的是授权
            let codestring = "code="
            if query!.hasPrefix(codestring) {
                let nsquery = query! as NSString
                let code = nsquery.substringFromIndex(codestring.characters.count)
                HTUserAccountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    //判断是否有错
                    if error != nil{
                        print("error:\(error)")
                        SVProgressHUD.showErrorWithStatus("获取 token失败 ")
                        // 延迟1秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        return
                    }
                    //没有错误
                    //关闭控制器
                    print("没有错误关闭控制器")
                   AppDelegate.delegateChangeController(HTWelcomeViewController())
                })
            }else{
                //点击了取消，不是授权
                //关闭界面
                close()
            }
            return false
        }
        
    }
}